#define _CRT_SECURE_NO_WARNINGS 1

#include"List.h"

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));

	if (NULL == newnode)
	{
		perror("malloc fail!");
		exit(1);
	}

	newnode->data = x;
	newnode->next = newnode->prev = newnode;

	return newnode;
}

LTNode* LTInit()
{
	LTNode* phead = LTBuyNode(-1);
	return phead;
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur!=phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead;
	newnode->prev = phead->prev;
	
	phead->prev->next = newnode;
	phead->prev = newnode;

}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* newnode = LTBuyNode(x);
	newnode->next = phead->next;
	newnode->prev = phead;

	phead->next->prev = newnode;
	phead->next = newnode;

}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->prev != phead);

	LTNode* del = phead->prev;
	LTNode* prev = del->prev;

	phead->prev = prev;
	prev->next = phead;

	free(del);
	del = NULL;

}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->prev != phead);

	LTNode* del = phead->next;
	LTNode* next = del->next;

	phead->next = next;
	next->prev = phead;
	
	free(del);
	del = NULL;

}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* pcur = phead->next;
	while (pcur->next)
	{
		if (x == pcur->data)
		{
			return pcur;
		}
		pcur = pcur->next;
	}

	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = (LTNode*)LTBuyNode(x);
	
	newnode->prev = pos;
	newnode->next = pos->next;
	
	pos->next->prev = newnode;
	pos->next = newnode;

}

void LTErase(LTNode* pos)
{
	assert(pos);
	
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;

}

void LTDestroy(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur->next!=phead)
	{
		free(pcur);
		pcur = NULL;
		pcur = pcur->next;
	}
	
	free(phead);
	phead = NULL;
}